#!/bin/sh

expiredate=`date`
#echo "$expiredate"

if [[ -z "$1" ]] ; then
	echo ""
	echo "Please give exactly one file name."
	echo "Each line will have:"
	echo "username"
	echo "group"
	echo "personal real name"
	echo ""
	echo "Sample line:"
	echo "alfreado marketing Alfredo de Darc"
	exit 1
fi

cat "$1" | while read username groupname realname
do
	#Skip blank lines
	if [[ -z $username || -z $groupname || -z $realname ]]; then
		continue
	fi

	result=$( egrep "^$username:" < /etc/passwd )
	
	if [[ -n "$result" ]] ; then
		echo "user '$username' already exists"
		continue
	fi

	result=$( egrep "^$groupname:" < /etc/group )

	if [[ -z "$result" ]] ; then
		groupadd "$groupname"
	fi

	useradd -c "$realname" \
		-d "/home/$username" \
		-e "$expriedate" \
		-f 365 \
		-g "$groupname" \
		-m \
		-s /bin/bash \
		"$username"

	if [[ $? == 0 ]]; then
		echo "Successfully added user '$username'."
	else
		echo "Error addind user '$username' (group \
			'$groupname' , realname '$realname')"
		exit 1
	fi

done
